import axios, { AxiosResponse, CancelTokenSource } from "axios";
import { message } from "antd";
import { judgeCode } from "./methods";

export interface ApiResponse<T> {
  success: boolean,
  msg: string,
  code: number,
  data: T
}

/** 
 * 1 默认的格式请求体中的数据以json字符串的形式发送到后端
 * Content-Type: application/json
 * 2 请求体中的数据以普通表单形式（键值对）发送到后端
 * Content-Type: application/x-www-form-urlencoded
 * 3 将请求体的数据处理为一条消息，以标签为单元，用分隔符分开。既可以上传键值对，也可以上传文件
 * Content-Type: multipart/form-data
 */
const baseURL = 'http://117.72.109.6:8000'
// const baseURL = 'http://127.0.0.1:8000'
// const baseURL = 'http://101.37.232.74:8000'


// 创建一个取消令牌源
let cancelTokenSource: CancelTokenSource | null = null;

axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
export const server: any = axios.create({
  baseURL,
  timeout: 30000,
  maxContentLength: Infinity,
  maxBodyLength: Infinity
}as any);


// 请求拦截
server.interceptors.request.use(
  (config: any) => {
    const token = sessionStorage.getItem('token')?.replace(/^"|"$/g, '') || '';
    
    if (token) {
      config.headers = {
        Authorization: token,
      };
    }

    // 为当前请求创建一个新的取消令牌源
    cancelTokenSource = axios.CancelToken.source();
    config.cancelToken = cancelTokenSource.token;
    return config;
  },
  (err: any) => {
    alert("请求超时");
    return Promise.reject(err);
  }
);

// 响应拦截
server.interceptors.response.use(
  (res: any) => {
    if (res.status === 200) {
      // messageApi.success(res.data)
    }
    if (res.status === 202) {
      alert(res.data || '网络异常')
    }
    if (res.status === 204) {
      alert(res.data || '网络异常')
    }
    return res?.data;
  },
  (err: { message: string; response: any; status: number}) => {
    console.log("response error", err.response)
    console.log(err?.status);
    alert(err?.response?.data?.message || '网络异常')
    
    if (err?.status === 401) {
      window.location.href = '/login'
    }
    if (err.message !== "所有请求被取消") {
      const response: AxiosResponse = err.response;
      if (response && response.status) judgeCode(response);
      return Promise.reject(err);
    }
  }
);

// 取消正在进行的请求的函数
export function cancelRequests() {
  if (cancelTokenSource) {
    cancelTokenSource.cancel("所有请求被取消");
    cancelTokenSource = null;
    // console.log(cancelTokenSource, "cancelTokenSource");
  }
}

export default server;
